from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.headlines.models import Article
from apps.headlines.serializers.image import ImageSerializer
from apps.headlines.utils import PageNum


class ArticleImage(ModelViewSet):
    """文章图片"""
    # 图片序列化器
    serializer_class = ImageSerializer
    # 图片查询集
    queryset = Article.objects.all()
    # 分页
    pagination_class = PageNum

    # 重写create方法保存图片
    def create(self, request, *args, **kwargs):
        # 导入fsatdfs包
        from fdfs_client.client import Fdfs_client
        # 创建链接对象
        client = Fdfs_client("apps/headlines/fastdfs/client.conf")
        # 获取前端传递的图片数据
        data = request.FILES.get("img")
        # 上传图片到fastDFS
        serializer = client.upload_appender_by_buffer(data.read())
        # 判断是否上传成功
        if serializer["Status"] != "Upload successed.":
            return Response(status=403)
        # 获取上传后的路径
        image_url = serializer['Remote file_id']
        # 保存图片
        img = Article.objects.create(image=image_url)
        # 返回响应
        return Response({"image":img.image_url})

    # 重写update方法用于更新图片数据
    def update(self, request, *args, **kwargs):
        # 导入fsatdfs包
        from fdfs_client.client import Fdfs_client
        # 创建链接对象
        client = Fdfs_client("apps/headlines/fastdfs/client.conf")
        # 获取前端传递的图片数据
        data = request.FILES.get("img")
        # 上传图片到fastDFS
        serializer = client.upload_appender_by_buffer(data.read())
        # 判断是否上传成功
        if serializer["Status"] != "Upload successed.":
            return Response(status=403)
        # 获取上传后的路径
        image_url = serializer["Remote file_id"]
        # 更新图片
        image = image_url
        # 保存更新后的图片
        image.save()
        # 返回结果
        return Response({"image":image.image.url})